package com.example.p001_interview02;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 写一个固定容量同步容器，拥有put和get方法，以及getCount方法，能够支持2个生产者线程以及10个消费者线程的阻塞调用
 * @param <T>
 */
public class Container01<T> {

    private int size = 41;
    private BlockingQueue<T> c = new LinkedBlockingQueue<>(size);

    public void put(T o) {
        try {
            c.put(o);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public T get() {

        T o = null;
        try {
            o = c.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return o;
    }

    public int getCount() {
        return c.size();
    }

    public static void main(String[] args) {

        Container01 c = new Container01();

        // 10个消费者
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + " 开始消费");
                for (int j = 0; j < 4; j++) {
                    Object o = c.get();
                    System.out.println(Thread.currentThread().getName() + " 获得：" + o);
                }
            }, "consumer" + i).start();
        }

        // 2个生产者
        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + " 开始生产");
                for (int j = 0; j < 20; j++) {
                    c.put(Thread.currentThread().getName() +  "-" + j);
                }
                System.out.println(Thread.currentThread().getName() + " 结束生产");

            }, "producter" + i).start();
        }

    }

}
